<?php

namespace App\Http\Controllers\Admin;


use App\CodeResponse;
use App\Exceptions\BusinessException;
use App\Imports\UsersImport;
use App\Models\ClassStudent;
use App\Models\Users;
use App\Services\SchoolService;
use App\Services\UsersServices;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use phpDocumentor\Reflection\Utils;

class UsersController extends AdminController
{
    private $usersService;

    public function __construct()
    {
        $this->usersService = UsersServices::getInstance();
    }

    public function user(){
        return Auth::guest('admin');

    }
    //添加用户
    public function  add(Request $request){

        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required',
            'name' => 'required',
            'school_id' => 'integer|digits_between:1,20|min:1',
            'sex' => 'integer|digits_between:1,20',
            'type' => 'required|integer',
            'age' => 'integer|digits_between:1,20',

            'role_id' => 'integer|digits_between:1,20|min:1',
            'pic' => 'string',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        if($request->type === 0){
            $validator = Validator::make($request->all(), [
                'student_num' => 'required|digits_between:1,20|min:1',
            ]);
            if ($validator->fails()) {
                return $this->fail(CodeResponse::PARAM_ILLEGAL);
            }
            $school =  SchoolService::getInstance()->getSchoolInfo($request->school_id);
            $StudentNum =  SchoolService::getInstance()->getSchoolStudentNum($request->school_id);
            if(!is_null($school) && $StudentNum  >= $school->student_num ){
                return $this->fail(CodeResponse::AUTH_SCHOOL_STUDENT_NUM);
            }

        }

        $validator = Validator::make($request->all(), [
            'phone' => 'regex:/^1[345789][0-9]{9}$/',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_PHONE_UNREGISTERED);
        }

        $validator = Validator::make($request->all(), [
            'email' => 'email:rfc,dns',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_MEAIL_UNREGISTERED);
        }

        $user =  UsersServices::getInstance()->getByUsresname($request->username);
        if(!is_null($user)){
            return $this->fail(CodeResponse::AUTH_NAME_REGISTERED);
        }
        $user =  UsersServices::getInstance()->getByPhone($request->phone);
        if(!is_null($user)){
            return $this->fail(CodeResponse::AUTH_PHONE_REGISTERED);
        }
        $user =  UsersServices::getInstance()->getByEmail($request->email);
        if(!is_null($user)){
            return $this->fail(CodeResponse::AUTH_MEAIL_REGISTERED);
        }

        $users = new Users();
        $users->username = $request->username;
        $users->password = Hash::make($request->password);
        $users->name = $request->name;
        $users->sex = $request->sex;
        $users->age = $request->age;
        $users->pic = $request->pic;
        $users->type = $request->type;
        $users->email = $request->email;
        $users->phone = $request->phone;
        $users->school_id = $request->school_id;
        $users->role_id = $request->role_id;

        if($request->type===0){
            $users->student_num = $request->student_num;
        }
        $users->last_login_time =Carbon::now()->toDateTimeString();
        $users->last_login_ip = $request->getClientIp();
        $users->save();
        return $this->success([
//            'token' => $token,
            'userInfo'=>[
                'username'=>$request->username,
                'picUrl'=>$request->pic,
            ]
        ]);
    }
    // 上传头像
    public function upfile(Request $request) {
        $url = config('filesystems.disks.users.url');
        $default = config('filesystems.disks.users.default');
        $pic =  UsersServices::getInstance()->upfile($request,$url,$default);
        return $this->success([
                'pic'=>$pic,
            ]
        );
    }
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
            'username' => 'required',
            'password' => 'required',
            'name' => 'required',
            'school_id' => 'integer|digits_between:1,20|min:1',
            'sex' => 'integer|digits_between:1,20',
            'type' => 'required|integer',
            'age' => 'integer|digits_between:1,20',
            'role_id' => 'integer|digits_between:1,20|min:1',
            'pic' => 'string',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        // if($request->type === 0) {
        //     $validator = Validator::make($request->all(), [
        //         'student_num' => 'required|integer|digits_between:1,20|min:1',
        //     ]);
        // }
        // if ($validator->fails()) {
        //     return $this->fail(CodeResponse::PARAM_ILLEGAL);
        // }

        $validator = Validator::make($request->all(), [
            'username' => 'unique:users,username,' . $request->id . ',id',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_NAME_REGISTERED);
        }
        $validator = Validator::make($request->all(), [
            'email' => 'unique:users,email,' . $request->id . ',id',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_MEAIL_REGISTERED);
        }
        $validator = Validator::make($request->all(), [
            'phone' => 'unique:users,phone,' . $request->id . ',id',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_PHONE_REGISTERED);
        }

        $putData = $request->except(['_method','_token','created_at','role_name']);
        $putData['password'] = Hash::make($request->password);
        $users = new Users();
        $users->find($request->id)->update($putData);
        return $this->success();

    }
    public function list(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'page' => 'integer',
            'limit' => 'integer',
            'username' => 'string',
            'name' => 'string',
            'school_id' => 'integer|digits_between:1,20|min:1',
            'role_id' => 'integer|digits_between:1,20|min:1',
            'type' => 'integer',
            'sort' => 'string',
            'order' => 'string',

        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $name = $request->input('name');
        $username = $request->input('username');
        $school_id = $request->input('school_id');
        $role_id = $request->input('role_id');
        $type = $request->input('type');
        $page = $request->input('page',1);
        $limit = $request->input('limit',10);
        $sort = $request->input('sort','created_at');
        $order = $request->input('order','desc');

        $list = UsersServices::getInstance()->listUsers($role_id,$username,$name,$school_id,$type,$page,$limit,$sort,$order);

        return $this->success($list);

    }
//获取用户信息
    public function userInfo(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'users_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $users = Users::select('username', 'name','pic','sex','age','student_num','last_login_ip','last_login_time','created_at')->find($request->users_id);
        return $this->success($users);
    }
    //删除
    public function delete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $users = Users::find($request->id);
        $users->delete();
        return $this->success();
    }
    //导入
    public function usersImport(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL,'类型未传');
        }


        $url = config('filesystems.disks.excel.url');
        $excelFile=  UsersServices::getInstance()->upfile($request,$url,'','excel');

        $data = Excel::toArray(new UsersImport,'./'.$excelFile);


        if (!empty($data)) {
            $arr = $data[0];
            if($request->type == 0){ //导入学生
                $school =  SchoolService::getInstance()->getSchoolInfo($request->school_id);
                $studentNum =  SchoolService::getInstance()->getSchoolStudentNum($request->school_id);
                if(!is_null($school) && $studentNum  >= $school->student_num ) {
                    return $this->fail(CodeResponse::AUTH_SCHOOL_STUDENT_NUM);
                }
                if (!is_null($school) && ($studentNum + count($arr)) > $school->student_num) {
                    return $this->fail(CodeResponse::AUTH_SCHOOL_STUDENT_NUM,'导入文件中学生数量已超过学校可添加学生数量，请您修改后在添加！');
                }
            }

            $newArr = [];
            foreach ($arr as $rows) {
                $arr2 = [];
                foreach ($rows as $v){
                    array_push($arr2,$v);
                }
                //必须传的值
                $mustArr =[
                    'username'=>$arr2[0],
                    'password'=>$arr2[1],
                    'name'=>$arr2[2],
                    'sex'=>$arr2[3],
                    'age'=>$arr2[4],
                    'phone'=>$arr2[5],
                    'email'=>$arr2[6],
                ] ;
                if($request->type == 1){ //导入教师
                    $mustArr['type'] = 1;
                }else if($request->type == 0){ //导入学生
                    $mustArr['student_num'] = $arr2[7];
                }

                $validator = Validator::make($mustArr, [
                    'username' => 'required',
                ]);
                if ($validator->fails()) {
                    return $this->fail(CodeResponse::PARAM_ILLEGAL,'用户名不能为空');
                }
                $validator = Validator::make($mustArr, [
                    'password' => 'required',
                ]);
                if ($validator->fails()) {
                    return $this->fail(CodeResponse::PARAM_ILLEGAL,'密码不能为空');
                }
                $validator = Validator::make($mustArr, [
                    'email' => 'email:rfc,dns',
                ]);
                if ($validator->fails()) {
                    return $this->fail(CodeResponse::AUTH_MEAIL_UNREGISTERED);
                }
                $validator = Validator::make($mustArr, [
                    'phone' => 'regex:/^1[345789][0-9]{9}$/',
                ]);
                if ($validator->fails()) {
                    return $this->fail(CodeResponse::AUTH_PHONE_UNREGISTERED);
                }

                array_push($newArr,$mustArr);
                $userNameNum = 0;
                $emailNum = 0;
                $phoneNum = 0;
                foreach ($newArr as $v){
                    if($v['username']==$mustArr['username']){
                        $userNameNum++;
                    }
                    if($v['email']==$mustArr['email']){
                        $emailNum++;
                    }
                    if($v['phone']==$mustArr['phone']){
                        $phoneNum++;
                    }

                    if($userNameNum >=2){
                        return $this->fail(CodeResponse::AUTH_NAME_REGISTERED,'文件里用户名'.$v['username'].'重复');
                    }
                    if($emailNum >=2){
                        return $this->fail(CodeResponse::AUTH_MEAIL_REGISTERED,'文件里邮箱'.$v['email'].'重复');
                    }
                    if($phoneNum >=2){
                        return $this->fail(CodeResponse::AUTH_PHONE_REGISTERED,'文件里手机号'.$v['phone'].'重复');
                    }

                    $user =  UsersServices::getInstance()->getByUsresname($v['username']);
                    if(!is_null($user)){
                        return $this->fail(CodeResponse::AUTH_NAME_REGISTERED,'系统里用户名'.$v['username'].'已存在');
                    }
                    $email =  UsersServices::getInstance()->getByEmail($v['email']);
                    if(!is_null($email)){
                        return $this->fail(CodeResponse::AUTH_MEAIL_REGISTERED,'系统里邮箱'.$v['email'].'已存在');
                    }
                    $phone =  UsersServices::getInstance()->getByPhone($v['phone']);
                    if(!is_null($phone)){
                        return $this->fail(CodeResponse::AUTH_PHONE_REGISTERED,'系统里手机号'.$v['phone'].'已存在');
                    }
                }
            }
            $n = 0;
//            dd($newArr);
            foreach ($newArr as  $v){

                $users = new Users();
                $users->username = $v['username'];
                $users->password = Hash::make($v['password']);
                $users->name = $v['name'];
                $users->sex = isset($v['sex']) ? $v['sex'] : 0;
                $users->age = isset($v['age']) ? $v['age'] : 0;
                $users->email = $v['email'];
                $users->phone = $v['phone'];

                $users->student_num = isset($v['student_num']) ? $v['student_num'] : null;
                $users->type = ($request->type ==1) ? 1 : 0;
                $users->school_id = $request->school_id;
                if($request->type ==1){
                    $users->role_id = 4; //教师角色
                }
                $users->save();
                if($request->type ==0){
                    $classStudent = new ClassStudent();
                    $classStudent->class_grades_id = isset($request->class_grades_id) ? $request->class_grades_id : null;
                    $classStudent->school_id = isset($request->school_id) ? $request->school_id : null;
                    $classStudent->users_id = $users->id;
                    $classStudent->save();
                }

                $n++;
            }
            return $this->success('共导入：'.$n.'条数据');
        }else{
            return $this->fail(CodeResponse::IMPORT_UNKNOWN,'无导入数据');
        }


    }

}
